package com.veinhorn.scrollgalleryview.loader;

import com.veinhorn.scrollgalleryview.util.LogUtil;
import ohos.agp.components.Image;
import ohos.agp.components.element.PixelMapElement;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;

import java.io.IOException;

/**
 * DefaultImageLoader
 *
 * @since 2021-05-13
 */
public class DefaultImageLoader implements MediaLoader {
    private int mId;
    private PixelMapElement mBitmap;

    /**
     * DefaultImageLoader
     *
     * @param id
     */
    public DefaultImageLoader(int id) {
        mId = id;
    }

    /**
     * DefaultImageLoader
     *
     * @param bitmap
     */
    public DefaultImageLoader(PixelMapElement bitmap) {
        mBitmap = bitmap;
    }

    /**
     * erewr
     *
     * @return 234
     */
    @Override
    public boolean isImage() {
        return true;
    }

    /**
     * loadMedia
     *
     * @param context
     * @param imageView
     * @param callback
     */
    @Override
    public void loadMedia(Context context, Image imageView, SuccessCallback callback) {
        // we aren't loading bitmap, because full image loaded on thumbnail step
        imageView.setImageElement(mBitmap);
        if (callback != null) {
            callback.onSuccess();
        }
    }

    /**
     * loadThumbnail
     *
     * @param context
     * @param thumbnailView
     * @param callback
     */
    @Override
    public void loadThumbnail(Context context, Image thumbnailView, SuccessCallback callback) {
        loadBitmap(context);
        thumbnailView.setImageElement(mBitmap);
        if (callback != null) {
            callback.onSuccess();
        }
    }

    private void loadBitmap(Context context) {
        // 根据资源生成PixelMapElement实例
        PixelMapElement pixBg = null;
        if (mBitmap == null) {
            try {
                Resource bgResource = context.getResourceManager().getResource(mId);
                pixBg = new PixelMapElement(bgResource);
            } catch (IOException e) {
                LogUtil.error("loadBitmap-IOException", e.getMessage());
            } catch (NotExistException e) {
                LogUtil.error("loadBitmap-NotExistException", e.getMessage());
            }
            mBitmap = pixBg;
        }
    }
}
